package rule

import (
	"fmt"
	streamCtx "gluenet/internal/glue-datasyncer/context"
	"gluenet/pkg/apis"
)

func PutRules(c *streamCtx.StreamContext) {
	var req = struct {
		UserId string        `json:"name"`
		File   string        `json:"file"`
		Rules  []interface{} `json:"rules"`
	}{}

	c.WebContext.ReadJSON(&req)
	c.Logger.Debugf("req %v", req)

	cfg, err := c.ConfigMapGeter(req.File)
	if err != nil {
		c.WebContext.JSON(apis.ResponseReqErr(fmt.Errorf("get config map %v", err), nil))
		return
	}

	groups, ok := cfg["groups"].([]interface{})
	if !ok {
		c.WebContext.JSON(apis.ResponseReqErr(fmt.Errorf("groups struct %v", err), cfg))
		return
	}

	var exist = false
	for _, rulei := range groups {
		rules := rulei.(map[string]interface{})
		if rules["name"] == req.UserId {
			rules["rules"] = req.Rules
			exist = true
		}
	}
	if !exist {
		groups = append(groups, map[string]interface{}{
			"name":  req.UserId,
			"rules": req.Rules,
		})
	}

	c.Logger.Debugf("rule data %v", cfg)
	if err := c.ConfigMapUpdater(cfg, req.File); err != nil {
		c.WebContext.JSON(apis.ResponseInterErr(fmt.Errorf("updater config %v", err), nil))
		return
	}

	c.WebContext.JSON(apis.ResponseOK(cfg))
}

func GetRules(c *streamCtx.StreamContext) {
	user_id := c.WebContext.Values().GetString("user_id")
	data := c.DB.Prom.QueryRules(user_id)
	c.WebContext.JSON(data)
}

func GetAlert(c *streamCtx.StreamContext) {
	user_id := c.WebContext.Values().GetString("user_id")
	data := c.DB.Prom.QueryAlerts(user_id)
	c.WebContext.JSON(data)
}

func PutRulesV2(c *streamCtx.StreamContext) {
	var req = struct {
		Rules []interface{} `json:"rules"`
	}{}

	c.WebContext.ReadJSON(&req)

	user_id := c.WebContext.Values().GetString("user_id")
	c.Logger.Debugf("req %v", req)

	cfg, err := c.ConfigMapGeter("/prometheus/rules/alerts.yml")
	if err != nil {
		c.WebContext.JSON(apis.ResponseReqErr(fmt.Errorf("get config map %v", err), nil))
		return
	}

	groups, ok := cfg["groups"].([]interface{})
	if !ok {
		c.WebContext.JSON(apis.ResponseReqErr(fmt.Errorf("groups struct %v", err), cfg))
		return
	}

	var exist = false
	for _, rulei := range groups {
		rules := rulei.(map[string]interface{})
		if rules["name"] == user_id {
			rules["rules"] = req.Rules
			exist = true
		}
	}
	if !exist {
		groups = append(groups, map[string]interface{}{
			"name":  user_id,
			"rules": req.Rules,
		})
	}

	c.Logger.Debugf("rule data %v", cfg)
	if err := c.ConfigMapUpdater(cfg, "/prometheus/rules/alerts.yml"); err != nil {
		c.WebContext.JSON(apis.ResponseInterErr(fmt.Errorf("updater config %v", err), nil))
		return
	}

	c.WebContext.JSON(apis.ResponseOK(cfg))
}
